package com.mobile.ado.contacts;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.mobile.ado.R;

public class ContactListAdapter extends BaseAdapter {

	private ArrayList<Contact> contacts;
	private ArrayList<Integer> selectedIndex;
	private LayoutInflater inflater;

	public ContactListAdapter(Context context, ArrayList<Contact> contacts,
			ArrayList<Integer> selectedIndex) {
		inflater = LayoutInflater.from(context);

		this.selectedIndex = selectedIndex;
		this.contacts = contacts;

	}

	@Override
	public int getCount() {
		return contacts.size();
	}

	@Override
	public Object getItem(int position) {
		return contacts.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {

		ViewHolder holder = null;

		if (convertView == null) {
			holder = new ViewHolder();

			convertView = inflater.inflate(R.layout.contact_list_items, null);
			holder.textView = (TextView) convertView
					.findViewById(R.id.contact_name);
			holder.imageView = (ImageView) convertView
					.findViewById(R.id.head_image);
			holder.checkBox = (CheckBox) convertView
					.findViewById(R.id.item_select);
			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		if (contacts.get(position).getPhoto() == null) {
			holder.imageView.setImageResource(R.drawable.righttopimage);
		} else {
			holder.imageView.setImageBitmap(contacts.get(position).getPhoto());
		}

		holder.textView.setText(contacts.get(position).getName());
		holder.checkBox.setSelected(false);
		holder.checkBox
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView,
							boolean isChecked) {
						if (isChecked == true) {
							selectedIndex.add(position);
						} else {
							selectedIndex.remove(position);
						}
					}
				});

		return convertView;
	}

}

class ViewHolder {
	TextView textView;
	ImageView imageView;
	CheckBox checkBox;
}
